import React, { useEffect, useState } from 'react'
import { Form, Button, Input, Toast, Switch, Popup, CascadePicker } from 'antd-mobile'
import styles from './index.module.less'
import { useLocation, useNavigate, useSearchParams } from 'react-router-dom'
import { list } from '@/static/city'
import type { PickerValue } from 'antd-mobile/es/components/picker'
import { delAdreslist, addAdreslist, updataAdreslist, updatadefault } from '@/utils/adress/index'
import Navbar from '@/comopnents/Navbar'
interface Addtype {
    province: any[]
    defaultStatus: boolean
    detailAddress: string
    name: string
    phoneNumber: string
}
export default function Index() {
    const [initVal, setInitVal] = useState({})
    //切换按钮
    let [checked, setChecked] = useState(false)
    //获取地址栏路径
    const [serchParms] = useSearchParams()
    let pathnae = serchParms.get('id')
    //获取从地址栏编辑按钮传递过来的值
    const { state } = useLocation()
    const [values, setValue] = useState<PickerValue[]>([])
    let add = {} as Addtype
    //如果是修改地址，表单回显
    if (state) {

        add = {
            defaultStatus: state.defaultStatus ? true : false,
            detailAddress: state.detailAddress,
            name: state.name,
            phoneNumber: state.phoneNumber,
            province: [state.province, state.city, state.region]

        }



    }
    useEffect(() => {
console.log(add.defaultStatus);

        setChecked(add.defaultStatus)
        setValue(add.province)
    }, [state])
    //添加或者删除成功跳转到地址栏
    const nagitave = useNavigate()
    async function addList(datas: {}) {
        let res: resType = await addAdreslist(datas)
        // console.log(res);
        if (res.code === 20000) {
            // console.log(111114);
            Toast.show({
                icon: 'success',
                content: '编辑成功'
            })
            nagitave('/my/adresspage')
        }
    }
    async function updtaList(datas: {}) {
        let res: resType = await updataAdreslist(datas)
        // console.log(res);
        if (res.code === 20000) {
            // console.log(111114);
            Toast.show({
                icon: 'success',
                content: '编辑成功'
            })
            nagitave('/my/adresspage')

        }
    }

    //表单校验完成
    const onFinish = (values: any) => {
        console.log(values);
        values.defaultStatus ? values.defaultStatus = 1 : values.defaultStatus = 0
        values.city = values.province[1]
        values.region = values.province[2]
        values.province = values.province[0]
        values.cityCode = ''
        values.postCode = ""
        values.tag = ""
        // console.log(values);
        //如果是更新按钮
        if (pathnae) {
            let vals = {
                ...state,
                ...values
            }
            // console.log(vals);
            updtaList(vals)
        } else {
            //如果是新建按钮
            addList(values)
        }
    }
    const [visible, setVisible] = useState(false)
    //删除按钮点击事件
    async function deletAdress(pathnae: string | null) {
        let res: resType = await delAdreslist(pathnae)
        if (res.code === 20000) {
            Toast.show({
                icon: 'success',
                content: '删除成功',
            })
            nagitave('/my/adresspage')
        }
    }


    async function switchdefault(val: any) {
        val ? val = 1 : val = 0
        let res: resType = await updatadefault(state.id, val)
        console.log(res);
        if (res.code === 20000) {
            Toast.show({
                content: '切换默认状态成功'
            })
        }

    }
    return (
        <div>
            < Navbar title='乐居'></Navbar>
            <div className={styles.forms}>

                <Form
                    initialValues={add}
                    requiredMarkStyle={'none'}
                    className={styles.formslist} layout='horizontal' onFinish={onFinish}
                    footer={
                        <div className={styles.subMitbtn}>
                            <Button block type='submit' className={styles.btnsubMit} color='primary' size='large'>
                                提交
                            </Button>
                        </div>
                    }>
                    <Form.Item name='name' label='姓名' rules={[{ required: true, message: '姓名不能为空!' }]}>
                        <Input placeholder='请输入姓名' />
                    </Form.Item>
                    <Form.Item name='phoneNumber' label='电话号码' rules={[{ required: true }, { pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/, message: '手机号校验错误' }]}>
                        <Input placeholder='请输入电话号码' />
                    </Form.Item>
                    <Form.Item name='province'
                        trigger='onConfirm'
                        label='所在城市'
                        onClick={() => {
                            setVisible(true)
                        }}
                        rules={[{ required: true, message: '请选择所在城市' }]}>
                        <CascadePicker
                            title='所在城市'
                            options={list}
                            visible={visible}
                            onConfirm={(val, extend) => {
                                setValue(val)
                                // console.log('onConfirm', val, val.join('-'), extend.items)
                                return val
                            }}
                            value={values}
                            onClose={() => {
                                setVisible(false)
                            }}
                        >
                            {value => value.length ? values : '选择地址'}
                        </CascadePicker>
                    </Form.Item>
                    <Form.Item name='detailAddress' label='详细地址' rules={[{ required: true, message: '请输入详细地址!' }]}>
                        <Input placeholder='请输入详细地址' />
                    </Form.Item>
                    <Form.Item name='defaultStatus' label='设置默认地址' childElementPosition='right'>
                        <Switch
                        className={styles.switchs}
                            checked={checked}
                            onChange={async val => {
                                await switchdefault(val)
                                setChecked(val)
                            }} />
                    </Form.Item>

                </Form>
                {pathnae && <div className={styles.deletAdre}>
                    <Button onClick={() => deletAdress(pathnae)} style={{ width: '90%' }} color='danger'>删除该地址</Button>
                </div>}
            </div>
            <div >
            </div>
        </div>
    )
}
